using System;
using UnityEngine;

public class PlanGoToObject : Plan
{

	private AgentBehaviourScript agent;
	private Maze maze;
	private GameObject thing;
	private Plan currentPlan = null;
	private Vector3 oldThingPosition;

	public PlanGoToObject (AgentBehaviourScript agent, Maze maze, GameObject thing)
	{
		this.agent = agent;
		this.maze = maze;
		this.thing = thing;
	}

	public override bool execute ()
	{
		Vector3 thingPosition;
		try
		{
			thingPosition = thing.transform.position;
			thingPosition.y = agent.getPosition().y;
		}
		catch
		{
			// Thing we are after no longer exists so end the plan - we may have eaten it
			return false;	
		}
		
		if (Vector3.Distance(thingPosition, oldThingPosition) < maze.getCellSize()*2.0f)
		{
			//Object has moved enough to warrent a new path	
			currentPlan = null;
		}
			
		if (currentPlan	== null)
		{
			currentPlan = new PlanPathFindToPosition(agent, maze, thingPosition);
			return true;
		} else
		{
			if (currentPlan.execute())
				return true; // plan continuing
			else
				return false; // plan finished
		}
	}
	
	public override pathplanner getPathPlanner() {
		
		if (currentPlan	!= null) {
			return currentPlan.getPathPlanner();
		} else {
			return null;
		}
		
	}
	
	public override string ToString ()
	{
		string returnString = string.Format ("GetThing( ");
		if (currentPlan != null)
			returnString += currentPlan.ToString();
		returnString += " )";
		return returnString;
	}	
	
}

